#! /bin/bash
#
# Copyright(C) 2013 yanyg <yygcode@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING, if not see
# <http://www.gnu.org/licenses/>.
#
# This script is used to prepare @LFS(Linux From Scratch) compile enviroment.
# Please source this script directly with proper options
#
# OPTIONS
#	-n, --dry-run		Just print the result enviroment
#	-p, --partition		root filesystem partition
#	-j, --jobs		simultianeously running jobs
# ENV
#

prog=env-prepare.sh

LOPTS="help,verbose,quiet,debug,dry-run,partition,jobs,arch"
SOPTS="h,v,q,d,n,p,j,a"
OPTIONS=$(getopt -l$LOPTS -o$SOPTS -n "$0" -- "$@") || exit $?
eval set -- "$OPTIONS"
unset LOPTS SOPTS OPTIONS

usage()
{
	local ex=${1:-1} f=1

	[ -n "${ex##*[!0-9]*}" ] || ex=1
	[ "$ex" -eq 0 ] || f=2

	cat >&$f << EOF

Usage: $prog: [option]...

Options:
	-h, --help			print usage
	-V, --version			print version
	-v, --verbose			verbose mode
	-q, --quiet			quiet mode
	-d, --debug			debug mode
	-n, --dry-run			just print results
EOF
	exit $ex
}

__echo_level()
{
	local level=$1; shift

	[  "$ECHO_LEVEL" -ge "$level" ] || return 0

	ECHO_PREFIX=(unused info verbose debug)

	echo "[${ECHO_PREFIX[$level]}] $@" >&2
}

echo_debug() { __echo_level 3 "$@"; }
echo_verbose() { __echo_level 2 "$@"; }
echo_normal() { __echo_level 1 "$@"; }
echo_exit() { echo "err: $@" >&2; exit 1; }

init_echo()
{
	ECHO_LEVEL=1

	[ "$#" -gt 0 ] || return 0

	local i args=$(eval echo {1..$#})

	for i in $args; do
		case "$(eval echo \${$i})" in
		--verbose|-v) ECHO_LEVEL=2;;
		--debug|-d) ECHO_LEVEL=3;;
		--quiet|-q) ECHO_LEVEL=0;;
		--) break;;
		*) ;;
		esac
	done

	echo_verbose "echo level=$ECHO_LEVEL"
}
init_echo "$@"
unset init_echo

ENVS="LFS_ROOT LFS_ARCH LFS_CPUNUM LFS_TARGET
      LFS_TARGET_LAST LFS_MAKEFLAGS LFS LFS_PARTITION
      SOURCES LFS_TMP LFS_MNT LFS_TOOLS LFS_UID"

verbose_vars()
{
	local x envs="LFS_ROOT LFS_ARCH LFS_CPUNUM LFS_TARGET
		      LFS_TARGET_LAST LFS_MAKEFLAGS LFS
		      SOURCES LFS_TMP LFS_MNT LFS_TOOLS
		      LFS_UID"

	[ -z "$(echo_verbose "dummy" 2>&1)" ] && return 0

	echo_verbose "$@:"
	for x in $envs; do
		printf "\t%-13s = '%s'\n" $x $(eval echo \$$x)
	done
	printf "\t%-13s = '%s'\n" PATH "$PATH"
}

echo_debug "Set env default values"
LFS_ROOT="$PWD"
LFS_ARCH=$(uname -m)
LFS_CPUNUM=$(cat /proc/cpuinfo | grep "^processor" | wc -l)

do_reset_env()
{
	LFS_TARGET=$LFS_ARCH-nwolf-linux-gnu
	LFS_TARGET_LAST=$LFS_ARCH-linux-gnu
	LFS_MAKEFLAGS="-j$LFS_CPUNUM"
	LFS_SOURCES="$LFS_ROOT/sources"
	LFS_TMP="$LFS_ROOT/tmp/$LFS_ARCH/haywire"
	LFS_MNT=$LFS_ROOT/mnt/$LFS_ARCH
	LFS_TOOLS="$LFS_MNT/tools"
	LFS_UID=$UID
}
do_reset_env
verbose_vars "Env default:"

echo_debug "Process echo options"
DRY_RUN=no
while [ $# -gt 0 ]; do
	case "$1" in
	--help|-h)	usage 0 ;;
	--verbose|-v)	: ;;
	--debug|-d)	: ;;
	--quiet|-q)	: ;;
	--dry-run|-n)	DRY_RUN=yes ;;
	--)		shift; break ;;
	*)		echo_normal "Unknown option -- '$1', ignore" ;;
	esac
	shift
done

echo_debug arguments-envs="'$@'"
eval "$@"
do_reset_env

[ "$DRY_RUN" = "yes" ] && {
	ECHO_LEVEL=3
	verbose_vars "Dry-run env result:"
	exit 0
}
unset DRY_RUN

do_prepare()
{
	local x

	[ -n "$LFS_PARTITION" ] || echo_exit "invalid LFS_PARTITION"
	[ -b "$LFS_PARTITION" ] || \
		echo_exit "invalid partiton $LFS_PARTITION"

	[ "$(readlink /tools 2>/dev/null)" != "$LFS_TOOLS" ] && {
		sudo ln -svf "$LFS_TOOLS" / || \
			echo_exit "ln $LFS_TOOLS fail"
	}
	[ "$(readlink /lfs-mnt 2>/dev/null)" != "$LFS_MNT" ] && {
		sudo ln -svf "$LFS_MNT" /lfs-mnt || \
			echo_exit "ln $LFS_MNT fail"
	}

	set +h
	umask 022
	LC_ALL=POSIX

	# reset LFS_TOOLS
	LFS_TOOLS=/tools
	[ -n "$(grep "$LFS_ROOT/bin" <<<$PATH)" ] || \
		PATH=$PATH:$LFS_ROOT/bin
	[ -n "$(grep "^$LFS_TOOLS/bin" <<<$PATH)" ] || \
		PATH=$LFS_TOOLS/bin:$PATH
}
do_prepare
unset do_prepare
verbose_vars "Env result:"

export $ENVS
echo_normal "LFS env init success"
unset __echo_level echo_debug echo_verbose echo_normal ECHO_LEVEL \
      usage verbose_vars do_reset_env ENVS

[ "$(basename -- "$0")" = "$prog" ] && { \
	echo "Run '$prog' directly is useless, Start a new bash !"
	exec /bin/bash
}
unset prog
